import { useState, useEffect, useRef } from "react";
import { useParams } from "react-router";
import ChatWindow from "@/components/chat/chat-window";
import { useConversationStore } from "@/store/useConversationStore";
import { useChatStore } from "@/store/useChatStore";
import { createWS, sendWSMessage } from "@/api/chat";
import type { WSClient } from "@/utils/ws";
import { useWSStore } from "@/store/useWSStore";
import RoleSidecard from "@/components/chat/role-sidecard";
import { roleApi } from "@/api/role";
import type { Role } from "@/types/role";

type Conversation = {
  id: string;
  // RoleName: string;
};

export default function ChatBox() {
  const ws = useRef<WSClient | null>(null);
  const { sessionId: id } = useParams();
  const { setSelectedId, selectedId, conversations } = useConversationStore();
  const { messages, addMessage } = useChatStore();
  const [roleId, setRoleId] = useState<number | null>(null);
  const [role, setRole] = useState<Role | null>(null);
  const [currentConversation, setCurrentConversation] =
    useState<Conversation | null>(null);
  useEffect(() => {
    const found = conversations.find((c) => c.id == id);
    setRoleId(found?.roleId || null);
    setCurrentConversation(found || null);
  }, [conversations, id]);

  useEffect(() => {
    if (id) setSelectedId(id);
    if (!selectedId) return;
    ws.current = createWS(selectedId);
    useWSStore.getState().setWS(selectedId, ws.current);
    return () => ws.current?.close();
  }, [selectedId]);

  useEffect(() => {
    if (roleId) {
      roleApi.getRoleById(roleId).then((role) => {
        if (role) {
          setRole(role.data);
        }
      });
    }
  }, [roleId]);

  const chatMessages = id ? messages.get(id) || [] : [];

  const sendMessage = async (message: string) => {
    if (message.trim()) {
      // 添加文本内容
      addMessage({
        id: Date.now().toString(),
        content: [
          {
            type: "text",
            content: message,
          },
        ],
        role: "user",
      });
    }
    await sendWSMessage(ws.current!, {
      message,
      sessionId: Number(selectedId),
      skillId: 0,
    });
  };

  return (
    <div className="min-w-full min-h-full flex">
      {currentConversation ? (
        <>
          <ChatWindow messages={chatMessages} sendMessage={sendMessage} />
          <RoleSidecard role={role || {}} ws={ws.current!} />
        </>
      ) : (
        <div className="text-center text-gray-500">not found</div>
      )}
    </div>
  );
}
